# CCNCore::Provision::Application::resolv.pm
# Copyright (C) 2006  Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

#
# For more information: http://carrierclass.net/
#
use strict; use warnings;

package CCNCore::Provision::Application::resolv;
use base qw(CCNCore::Provision::Base);
use CCN::Text;
use CCNCore::Scripting;


sub run()
{
    my $self = shift;
    return if $self->p->force_manager;
    
    $self->CHECKFOR ('/etc/resolv.conf');

    # It seems mailname does not exist on Debian.
    # $self->CHECKFOR ('/etc/mailname');
    CAT '/etc/mailname', $self->p->server_name()."\n";

    # 127.0.0.1 + the masters as backup
    my $ns = "nameserver 127.0.0.1\n";
    $self->sql_do_for( q(SELECT id FROM server WHERE the_system = ? AND dns_master = 'TRUE'), $self->p->system_pk,
    sub
    {
        my $server_pk = shift;
        return if $server_pk eq $self->p->server_pk;
        my $ip = $self->primary_ip($server_pk);
        $ns .= "nameserver $ip\n" if defined $ip and $ip ne '';
    });

    CAT '/etc/resolv.conf', "search ".$self$self->p->system_name()."\n$ns\n";

    # TBD Probably most services need to be restarted if resolv.conf is modified.
    IF_CHANGED '/etc/resolv.conf', '/etc/init.d/ssh restart';

    my $my_ip = $self->primary_ip($self->p->server_pk);
    my $my_name = $self->p->server_name;

    CAT '/etc/hosts', <<"EOT";
127.0.0.1       localhost.localdomain   localhost
$my_ip          $my_name

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts
EOT

    CAT '/etc/hostname', $self->p->server_name."\n";
    IF_CHANGED '/etc/hostname', '/bin/kill -HUP 1'; # YYY ?
    IF_CHANGED '/etc/hostname', '/bin/hostname -F /etc/hostname';
}
1;